package fr.unice.polytech.chord.samples.commands;

import fr.unice.polytech.chord.core.ChordNode;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 10/30/2009
 */
public class LeaveCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public LeaveCommand(Manager manager) {
		super(manager, "Asks to a node with a given key to leave the overlay",
				new String[] { "leave" }, new String[] { "key" });
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		Key keyOfNodeToFind = null;
		try {
			keyOfNodeToFind = new Key(Integer.parseInt(args[0]));
		} catch (Exception e) {
			super.printInfo("Key argument must be a number");
			return;
		}

		if (args.length == 1) {
			ChordNode node = super.getManager().getTracker().getRandomPeer()
					.findSuccessor(keyOfNodeToFind);

			if (node.getKey().compareTo(keyOfNodeToFind) != 0) {
				super.printInfo("Node with key " + keyOfNodeToFind
						+ " does not exist on the overlay");
			} else {
				node.leave();
				super.printInfo("Node with key " + keyOfNodeToFind
						+ " has left the overlay");
			}
		} else {
			super
					.printInfo("Leave operation must have one argument which is the key of the chord node which must leave.");
		}
	}
}
